package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Class self = this.getClass();
        String method = request.getParameter("method");

        try {
            Method method1 = self.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);

            String invoke = (String) method1.invoke(this, request, response);

            if (invoke != null) {
                if (invoke.startsWith("forward:")) {

                    String path = invoke.substring(invoke.indexOf(":") + 1);
                    request.getRequestDispatcher(path).forward(request, response);

                } else if (invoke.startsWith("redirect:")) {

                    String path = invoke.substring(invoke.indexOf(":") + 1);
                    response.sendRedirect(request.getContextPath() + path);

                } else {
                    response.getWriter().println(invoke);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }
}
